package com.example.translateappjava.Activity;

import static android.app.PendingIntent.getActivity;

import static com.example.translateappjava.Fragment.ShuaFragment.messageAdapter;
import static com.example.translateappjava.Fragment.ShuaFragment.messageList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.CursorWindow;
import android.graphics.Bitmap;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.fragment.app.FragmentTransaction;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;
import androidx.appcompat.widget.Toolbar;

import com.example.translateappjava.Fragment.HomeFragment;
import com.example.translateappjava.Fragment.KnowledgeFragment;
import com.example.translateappjava.Fragment.MineFragment;
import com.example.translateappjava.Fragment.ShuaFragment;
import com.example.translateappjava.R;
import com.example.translateappjava.Service.AliyunAPI.AliyunAPIHelper;
import com.example.translateappjava.Service.ChatGPT.ChatGptHelper;
import com.example.translateappjava.Service.DiabetesFoodAdvisor;
import com.example.translateappjava.Service.FoodCalories.FoodCaloriesHelper;
import com.example.translateappjava.Service.FoodDetails.FoodDetailsHelper;
import com.example.translateappjava.Service.MedicalAtlas.MedicalAtlasHelper;
import com.example.translateappjava.Utils.Message;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity implements AliyunAPIHelper.AliyunAPIListener, MedicalAtlasHelper.MedicalAtlasListener , FoodDetailsHelper.FoodDetailsListener, FoodCaloriesHelper.FoodCaloriesListener , ChatGptHelper.OnChatGptResponseListener {
    private Bitmap bm;
    private ActivityResultLauncher<Intent> cameraLauncher;
    private ActivityResultLauncher<String> galleryLauncher;
    private BottomNavigationView bottomNavigationView;
    private HomeFragment mHomeFragment;
    private MineFragment mMineFragment;
    private KnowledgeFragment mKnowledgeFragment;

    private ShuaFragment mShuaFragment;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        increaseCursorWindowSize();

        setContentView(R.layout.activity_main);

        // Set background color
//        setBackGroundColor(MainActivity.this);

        // Set event listeners
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ImageView imageViewShot = findViewById(R.id.imageViewShot);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) SearchView searchViewSearch = findViewById(R.id.imageViewSearch);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout);
        //初始化控件
        bottomNavigationView = findViewById(R.id.bottomNavigationView);

        selectedFragment(0);
        // Search event


        //点击切换事件
        bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                if (menuItem.getItemId() == R.id.action_home) {
                    selectedFragment(0);
                } else if (menuItem.getItemId() == R.id.action_knowledge) {
                    selectedFragment(1);
                } else if (menuItem.getItemId() == R.id.action_shua) {
                    selectedFragment(2);
                }else if (menuItem.getItemId() == R.id.action_mine){
                    selectedFragment(3);
                }
                return true;
            }
        });


        applyColorSettings();

//        MedicalAtlasHelper.MedicalAtlasListener medicalAtlasListener = (MedicalAtlasHelper.MedicalAtlasListener) MainActivity.this;
//        MedicalAtlasHelper medicalAtlasHelper = new MedicalAtlasHelper(MainActivity.this);
//        medicalAtlasHelper.setMedicalAtlasListener(medicalAtlasListener);
//        medicalAtlasHelper.MedicalAtlasRequest("艾滋病");

    initView();
    }
        @Override
        protected void onStart () {
            super.onStart();

        }



        private void showChooseImageDialog () {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_choose_image, null);
            builder.setView(dialogView);
            AlertDialog dialog = builder.create();
            dialog.show();

            Button btnCamera = dialogView.findViewById(R.id.btnCamera);
            btnCamera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraLauncher.launch(cameraIntent);
                    dialog.dismiss();
                }
            });

            Button btnGallery = dialogView.findViewById(R.id.btnGallery);
            btnGallery.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    galleryLauncher.launch("image/*");
                    dialog.dismiss();
                }
            });
        }


        private void hideFragment (FragmentTransaction fragmentTransaction){
            if (mHomeFragment != null) {
                fragmentTransaction.hide(mHomeFragment);
            }
            if (mKnowledgeFragment != null) {
                fragmentTransaction.hide(mKnowledgeFragment);
            }
            if (mMineFragment != null) {
                fragmentTransaction.hide(mMineFragment);
            }
            if (mShuaFragment != null){
                fragmentTransaction.hide(mShuaFragment);
            }
        }


        private void selectedFragment ( int position){
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideFragment(fragmentTransaction);

            if (position == 0) {
                hideFragment(fragmentTransaction);
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                    fragmentTransaction.add(R.id.content, mHomeFragment);
                } else {
                    fragmentTransaction.show(mHomeFragment);
                }
            } else if (position == 1) {
                hideFragment(fragmentTransaction);
                if (mKnowledgeFragment == null) {
                    mKnowledgeFragment = new KnowledgeFragment();
                    fragmentTransaction.add(R.id.content, mKnowledgeFragment);
                } else {
                    fragmentTransaction.show(mKnowledgeFragment);
                }
            } else if (position == 2){
                hideFragment(fragmentTransaction);
                if (mShuaFragment == null) {
                    mShuaFragment = new ShuaFragment();
                    fragmentTransaction.add(R.id.content, mShuaFragment);
                } else {
                    fragmentTransaction.show(mShuaFragment);
                }
            } else if (position == 3){
                hideFragment(fragmentTransaction);
                if (mMineFragment == null) {
                    mMineFragment = new MineFragment();
                    fragmentTransaction.add(R.id.content, mMineFragment);
                } else {
                    fragmentTransaction.show(mMineFragment);
                }
            }

            fragmentTransaction.commit();
        }

        public static void setBackGroundColor (Activity activity){
            // 获取Context对象
            Context context = activity.getApplicationContext();
            // 定义更多的颜色，创建一个更加丰富的渐变效果
            int[] colors = context.getResources().getIntArray(R.array.forest_gradient_colors);
            // 设置渐变方向为左上到右下
            GradientDrawable.Orientation orientation = GradientDrawable.Orientation.TL_BR;

            // 创建渐变背景
            GradientDrawable gradientDrawable = new GradientDrawable(orientation, colors);
            // 设置背景
//        gradientDrawable.setAlpha(90);
            activity.getWindow().getDecorView().setBackground(gradientDrawable);
        }


    @Override
    public void AliyunAPIResponse(String response, int index) {
        if (response.equals("非菜")) {
            Toast.makeText(MainActivity.this, "该图片内容并非食物，请重新上传", Toast.LENGTH_SHORT).show();
        } else {
            DiabetesFoodAdvisor advisor = new DiabetesFoodAdvisor(MainActivity.this);
            String foodRecognitionResult = response;
            advisor.processFoodRecognitionResult(foodRecognitionResult,bm);
        }
    }

    @Override
    public void AliyunAPIError(String message) {

    }

    @Override
    public void onMedicalAtlasResponse(String response) {
        System.out.println(response);
    }

    @Override
    public void getFoodCaloriesResponse(String response) {
        System.out.println(response);
        FoodDetailsHelper.FoodDetailsListener foodDetailsListener = (FoodDetailsHelper.FoodDetailsListener) MainActivity.this;
        FoodDetailsHelper foodDetailsHelper = new FoodDetailsHelper(MainActivity.this);
        foodDetailsHelper.setFoodDetailsListener(foodDetailsListener);
//        foodDetailsHelper.getFoodDetailsResponse();
    }

    @Override
    public void getFoodDetailsResponse(String response) {
        System.out.println(response);
    }

    @Override
    public void onChatGptResponse(String response) {

        try {
            System.out.println(response);
            JSONObject jsonResponse = new JSONObject(response.toString());
            JSONArray choices = jsonResponse.getJSONArray("choices");
            JSONObject message = choices.getJSONObject(0).getJSONObject("message");
            String content = message.getString("content");
            messageList.add(new Message(content, false));
            messageAdapter.notifyItemInserted(messageList.size() - 1);
        }
        catch (JSONException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onError(String message) {

    }
    @Override
    public void onResume() {
        super.onResume();
        applyColorSettings(); // 再次调用 applyColorSettings() 以确保颜色设置
    }
    private void applyColorSettings() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        int defaultColor = getResources().getColor(R.color.toolbar_color); // 默认颜色
        int color = sharedPreferences.getInt("color", defaultColor); // 如果未找到颜色，则使用默认颜色
        BottomNavigationView btmNav = findViewById(R.id.bottomNavigationView);

        // 应用颜色到您想要更改的视图
        btmNav.setBackgroundColor(color);

        // 如果有其他视图也需要应用颜色，也可以在这里设置

    }
    public static void increaseCursorWindowSize() {
        try {
            Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize");
            field.setAccessible(true);
            field.set(null, 1024 * 1024 * 100); // 设置为 100MB
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        SharedPreferences sp=getSharedPreferences("this",MODE_PRIVATE);
        boolean is=sp.getBoolean("ok",true);
        //判断是否为第一次打开软件
        if (is){
            SharedPreferences.Editor editor=sp.edit();
            editor.putBoolean("ok",false);
            editor.apply();
            //跳转到引导页
            startActivity(new Intent(MainActivity.this,IntroductoryActivity.class));
            finish();
        }else {
            //直接进入首页

        }




}
}

